<template>
    <div id="drone" class="drone-view">
        <Map ref="mapRef" @map-loaded="onMapLoaded" @full-screen="handleFullScreen('drone')" />
        <!-- 顶部控制面板 -->
        <div class="control-panel">
            <CesiumButton type="primary" :disabled="!isMapReady" @click="toggleFlight">
                {{ isFlying ? '停止飞行' : '开始飞行' }}
            </CesiumButton>
            <CesiumButton type="warning" :disabled="!isMapReady" @click="resetFlight">
                重置飞行
            </CesiumButton>
            <CesiumButton type="info" :active="showParamsPanel" @click="toggleParamsPanel">
                飞行参数
            </CesiumButton>
        </div>

        <!-- 飞行参数输入面板 -->
        <CesiumPanel v-model="showParamsPanel" title="飞行参数设置" class="flight-params-panel">
            <template #header-buttons>
                <CesiumButton size="small" :disabled="!isValidJson" @click="applyParams">
                    应用参数
                </CesiumButton>
                <CesiumButton size="small" @click="resetParams">
                    重置默认
                </CesiumButton>
            </template>

            <el-input v-model="flightParamsInput" type="textarea" :rows="20" :class="{ 'error': !isValidJson }"
                @input="validateInput" placeholder="请输入飞行参数 JSON" />

            <div class="validation-message" v-if="!isValidJson">
                {{ validationMessage }}
            </div>
        </CesiumPanel>
    </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import Map from '@/components/Map.vue'
import FlightControl from '@/utils/flightControl'
import flightConfig from '@/config/flightPath.json'
import * as Cesium from 'cesium'
import { ElMessage } from 'element-plus'
import { CesiumButton, CesiumPanel } from '@/components/cesium'

const mapRef = ref(null)
const isMapReady = ref(false)
const isFlying = ref(false)
const flightParamsInput = ref('')
const isValidJson = ref(true)
const validationMessage = ref('')
let flightControl = null

// 添加面板显示状态控制
const showParamsPanel = ref(false)

// 切换参数面板显示
const toggleParamsPanel = () => {
    showParamsPanel.value = !showParamsPanel.value
}

// 初始化默认参数
flightParamsInput.value = JSON.stringify(flightConfig, null, 2)

// 验证飞行参数格式
const validateFlightParams = (params) => {
    try {
        if (!params.flightPath || !Array.isArray(params.flightPath)) {
            return { valid: false, message: '缺少 flightPath 数组' }
        }

        for (const point of params.flightPath) {
            // 验证位置参数
            if (!point.position ||
                typeof point.position.longitude !== 'number' ||
                typeof point.position.latitude !== 'number' ||
                typeof point.position.height !== 'number') {
                return { valid: false, message: '位置参数格式错误' }
            }

            // 验证方向参数
            if (!point.orientation ||
                typeof point.orientation.heading !== 'number' ||
                typeof point.orientation.pitch !== 'number' ||
                typeof point.orientation.roll !== 'number') {
                return { valid: false, message: '方向参数格式错误' }
            }

            // 验证时间参数
            if (typeof point.time !== 'number') {
                return { valid: false, message: '时间参数格式错误' }
            }
        }

        return { valid: true, message: '' }
    } catch (error) {
        return { valid: false, message: '参数格式错误' }
    }
}

// 验证输入
const validateInput = () => {
    try {
        const params = JSON.parse(flightParamsInput.value)
        const validation = validateFlightParams(params)
        isValidJson.value = validation.valid
        validationMessage.value = validation.message
    } catch (error) {
        isValidJson.value = false
        validationMessage.value = 'JSON 格式错误'
    }
}

// 应用新参数
const applyParams = () => {
    try {
        const params = JSON.parse(flightParamsInput.value)
        const validation = validateFlightParams(params)

        if (!validation.valid) {
            ElMessage.error(validation.message)
            return
        }

        // 停止当前飞行
        if (isFlying.value) {
            flightControl.stopFlight()
            isFlying.value = false
        }

        // 初始化新的飞行路径
        const flightPath = processFlightPath(params.flightPath)
        flightControl.initializeFlightPath(flightPath)
        ElMessage.success('飞行参数已更新')
    } catch (error) {
        ElMessage.error('参数应用失败')
    }
}

// 重置为默认参数
const resetParams = () => {
    flightParamsInput.value = JSON.stringify(flightConfig, null, 2)
    validateInput()
    applyParams()
}

// 处理角度转弧度
const processFlightPath = (path) => {
    return path.map(point => ({
        ...point,
        orientation: {
            heading: Cesium.Math.toRadians(point.orientation.heading),
            pitch: Cesium.Math.toRadians(point.orientation.pitch),
            roll: point.orientation.roll
        }
    }))
}

let cesiumTools = null
// 地图加载完成的回调
const onMapLoaded = (tools, viewer) => {
    console.log('Map loaded')
    cesiumTools = tools
    flightControl = new FlightControl(viewer)
    isMapReady.value = true

    // 初始化飞行路径
    const flightPath = processFlightPath(flightConfig.flightPath)
    flightControl.initializeFlightPath(flightPath)
}

// 切换飞行状态
const toggleFlight = () => {
    if (!flightControl) return

    if (isFlying.value) {
        flightControl.stopFlight()
    } else {
        flightControl.startFlight(() => {
            isFlying.value = false
        })
    }
    isFlying.value = !isFlying.value
}

// 重置飞行
const resetFlight = () => {
    if (!flightControl) return
    flightControl.resetFlight(processFlightPath(flightConfig.flightPath)[0])
    isFlying.value = false
}

// 添加全屏处理方法
const handleFullScreen = (id) => {
    cesiumTools.divFullScreen(id)
}

onBeforeUnmount(() => {
    if (flightControl) {
        flightControl.destroy()
    }
})
</script>

<style scoped lang="scss">
.drone-view {
    width: 100%;
    height: 100vh;
    position: relative;
}

.control-panel {
    position: absolute;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    display: flex;
    gap: 10px;
}

.flight-params-panel {
    position: absolute;
    top: 70px;
    left: 20px;
    z-index: 999;

    :deep(.el-textarea__inner) {
        background: #1a1a1a;
        border: 1px solid #444;
        color: #edffff;
        font-family: monospace;
        resize: none;

        &::-webkit-scrollbar {
            width: 10px;
            height: 10px;
        }

        &::-webkit-scrollbar-track {
            background: #202020;
            border-radius: 5px;
        }

        &::-webkit-scrollbar-thumb {
            background: #888;
            border: 2px solid #202020;
            border-radius: 5px;

            &:hover {
                background: #aaa;
            }
        }

        &::-webkit-scrollbar-corner {
            background: #202020;
        }

        &:focus {
            border-color: #409eff;
        }

        &.error {
            border-color: #f56c6c;
        }
    }

    .validation-message {
        color: #f56c6c;
        font-size: 12px;
        margin-top: 8px;
        min-height: 20px;
    }
}
</style>